package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session){
        try {
//            Employee employee = employeeService.login(username, password);
//            //将获取到的employee对象存入session中
//            //session.setAttribute("EMPLOYEE_IN_SESSION",employee);
//            UserContext.setCurrentUser(employee);
//            //判断当前用户是否为超管,如果是超管则不需要去查询权限
//            if (!employee.isAdmin()) {
//                //在登录成功的时候就去查询当前用户所拥有的所有的权限
//                List<String> expressions = permissionService.selectByEmpId(employee.getId());
//                //将获取的权限存入到session中
//                //session.setAttribute("PERMISSION_IN_SESSION",expressions);
//                UserContext.setPermission(expressions);
//            }

            //封装token
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            //需要利用shiro的api进行登录
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,"账户名不正确");
        } catch ( IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false,"密码不正确");
        } catch (DisabledAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,"账号已被禁用,请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"登录异常,请联系管理员");
        }
    }

/*
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //销毁session的数据
        session.invalidate();
        return "redirect:/login.html";
    }*/


}
